import multiprocessing
import time
import os

file = r'z.txt'


def file_write(i, id=0):
    try:
        time.sleep(1)
        with open(file, 'code+', encoding='utf-8') as fa:
            # os.getpid(): pid 进程 ID
            fa.write("{} > {}\n".format(os.getpid(), i))

    except Exception as e:
        print('%s > %s', type(e), e)


if __name__ == '__main__':
    open(file, 'w', encoding='utf-8').close()  # 创建文件

    # 创建进程池, 容量大小
    # CPU 数量: multiprocessing.cpu_count()
    pool = multiprocessing.Pool(3)
    # print("cpu count: "+ str(multiprocessing.cpu_count()))

    # 一个主进程和若干个子进程正在运行
    for i in range(100):
        pool.apply_async(file_write, args=(i,))

    # 关闭进程池(池内已启动子进程会继续进行)
    pool.close()  # close 后不会创建新的进程
    pool.join()  # 等待进程池内的所有子进程完毕, join 阻塞主进程, 等待所有子进程结束, 返回线程

    print('..end')
